<html>
<head>
<title>机构管理</title>
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8"/>

<link rel="shortcut icon" href="/static/images/lock.png" type="image/x-icon">
<link rel="stylesheet" href="/static/css/stylemain.css">
<link rel="stylesheet" href="/static/layui/css/layui.css">

<link rel="stylesheet" href="/static/layui/css/treeTable.css">
<link rel="stylesheet" href="/static/font-awesome-4.7.0/css/font-awesome.min.css" media="all">
<script src="/static/layui/layui.all.js"></script>
<script type="text/javascript" src="/static/js/jquery.js"></script>
<script type="text/javascript" src="/static/js/base64.js"></script>
</head>
<body>
<div class="layui-form" style="margin-top:10px">
<table id="tbl_org" class="layui-table" lay-filter="tbl_org"></table>
</div>
<script type="text/html" id="tbBar">
<button class="layui-btn layui-btn-sm" lay-event="add"><i class="layui-icon layui-icon-add-circle"></i> 添加</button>
<button class="layui-btn layui-btn-sm layui-btn-danger" lay-event="del"><i class="layui-icon layui-icon-delete"></i> 删除</button>
<button class="layui-btn layui-btn-sm" lay-event="edit"><i class="layui-icon layui-icon-edit"></i> 修改</button>
<input type="text" id="c_search" placeholder="机构名称查询" style="width:150px;height:24px;font-size: 12px;margin-left:10px" class="ckinput">
<button type="button" id="btn_search" style="margin-left:5px" class="layui-btn layui-btn-primary layui-btn-sm" lay-event="search"><i class="fa fa-search" aria-hidden="true"></i>查询</button>
</script>

<script id="orgadd" type="text/html">
	<form class="layui-form" action="" style="margin-top:20px;width:360px">
		<div class="layui-form-item">
		    <label class="layui-form-label">机构编码</label>
		    <div class="layui-input-block">
		      <input type="text" id="orgcode" name="orgcode" lay-verify="required" lay-reqtext="机构编码是必填项，岂能为空？" placeholder="请输入" autocomplete="off" class="layui-input">
		    </div>
		  </div>
		  <div class="layui-form-item">
	    	<label class="layui-form-label">机构名称</label>
		    <div class="layui-input-block">
		      <input type="text" id="orgname" name="orgname" lay-verify="required" lay-reqtext="机构编码是必填项，岂能为空？" placeholder="请输入" autocomplete="off" class="layui-input">
		    </div>
	  	</div>
	  	<div class="layui-form-item">
	    	<label class="layui-form-label">上级机构</label>
		    <div class="layui-input-block">
		      <input type="button" id="f_orgname" name="parentorg" onclick="dialog_orgselect('porg')" class="layui-input" style="text-align: left;">
		    </div>
	  	</div>
	  	<div class="layui-form-item">
	    	<label class="layui-form-label">管理机构</label>
		    <div class="layui-input-block">
		      <input type="button" id="f_managerorg" name="managerorg" onclick="dialog_orgselect('morg')" class="layui-input" style="text-align: left;">
		    </div>
	  	</div>
	  	<div class="layui-form-item">
	    	<label class="layui-form-label">所在地</label>
		    <div class="layui-input-block">
		      <input type="text" id="address" name="address" autocomplete="off" class="layui-input">
		    </div>
	  	</div>
	  	<div class="layui-form-item">
	    	<label class="layui-form-label">负责人</label>
		    <div class="layui-input-block">
		      <input type="text" id="leader" name="leader" autocomplete="off" class="layui-input">
		    </div>
	  	</div>	  	 
		  <div class="layui-form-item layui-form-text">
		    <label class="layui-form-label">备注</label>
		    <div class="layui-input-block">
		      <textarea id="descriptor" name="descriptor" placeholder="请输入内容" class="layui-textarea"></textarea>
		    </div>
		  </div>
		  <input id="org_id" type="text" name="org_id" style="display:none"></input>
		  <input id="morg_id" type="text" name="morg_id" style="display:none"></input>
	</form>
</script>

<script>
var _getorg = "";
var util = layui.util;
var layer = layui.layer;
var treetable;
var curopt = "";
var _searchval = "";
var insTb;
layui.config({
    base: '/static/layui/lay/modules/'
}).use(['treeTable'], function () {
    treetable = layui.treeTable;
    
    
    getData();
    
    function getData(){
    	
    	$.ajax({
    		type:"post",
    		contentType: "application/json;charset=UTF-8",
    		url: "orgfortreetable",
    		async:false,
         	dataType:"json",
            success: function(msg) {    //数据提交成功时返回数据
            	//debugger;
            	// 渲染表格
                insTb = treetable.render({
                    elem: '#tbl_org',
                    data: msg,
            		height: 'full-10',
            		toolbar: '#tbBar',
            		defaultToolbar: ['filter'],
            		tree: {
                        iconIndex: 1,
                        isPidData: true,
                        arrowType: 'arrow2',
                        getIcon: 'ew-tree-icon-style2',
                        onlyIconControl:true
                    },
            		cols: [
            			{type: 'radio', hide: true},
            			{
            				field: 'title',
            				title: '机构名称',	
            				width: '420px',
            			},
            			{
            				field: 'orgcode',
            				title: '机构编码',   
            				width: '120px',
            			},
            			{
            				field: 'manager_name',
            				title: '管理机构',
            			},
            			{
            				field:'leader',
            				title: '负责人',	
            				width: '100px',
            			},
            			{
            				field:'address',
            				title: '机构地址',				
            			},
            			{
            				field:'descriptor',
            				title: '备注',				
            			}
            		],
            		style: 'margin-top:0;',
            		done: function(res, curr, count){            			
            			$('#c_search').val(_searchval);
            			if(_searchval.length > 1){
            				insTb.filterData(_searchval);
            			}
            			
            		}
                });
    			
                treetable.on('row(tbl_org)', function(obj){
            	    var data = obj.data;    
            	    obj.tr.addClass('layui-table-click').siblings().removeClass('layui-table-click');
            		//选中radio样式
            		obj.tr.find('i[class="layui-anim layui-icon"]').trigger("click");
            	});
            },
            error : function(e){
                alert(e.status);
                alert(e.responseText);
            }

    	});
    }
    
    treetable.on('toolbar(tbl_org)', function (obj) {
    	//debugger;
    	var datas = insTb.checkStatus();
        switch (obj.event) {
            case 'add':
            	curopt = "add";
            	dialog_add();
                break;
            case 'del':
            	curopt = "del";
            	if(datas.length == 0){
            		layer.msg('请先选择机构!');
            		return;
            	}
                u_remove('','');
                break;
            case 'edit':
            	curopt = "edit";            	
            	dialog_edit(datas[0]);
                break;
            case 'search':
            	curopt = "search";            	
            	_searchval = $('#c_search').val().replace(/\s+/g,"");
            	if(_searchval.length > 1){
            		insTb.filterData(_searchval);
            	}else{
            		getData();
            	}            	
                break;
        }
    });    
    
    function dialog_add(){
    	var win = layer.open({
    		  type: 1 //0（信息框，默认）1（页面层）2（iframe层）3（加载层）4（tips层） 
    		  ,title: "添加机构" //标题
    		  ,skin:"layui-layer-lan"   //layui-layer-lan:蓝色，layui-layer-molv：墨绿色，默认灰色
    		  ,area: ['400px', '620px'] //宽度、高度
    		  ,shade: 0.3
    		  ,offset: 'auto'
    		  ,anim:5 //弹出动画
    		  ,shadeClose: false //弹框出现后，允许点击其它地方关闭
    		  ,content: $("#orgadd").html()     //内容
    		  ,btn: ['确定', '取消'] //只是为了演示
    		  ,success:function(layero){
    			     var mask = $(".layui-layer-shade");
    			     mask.appendTo(layero.parent());
    			     //其中：layero是弹层的DOM对象
    			     $('#orgcode').removeAttr("disabled");
    			     //form.render();
    			}
    		,yes: function(index, layero){
    		    //按钮【按钮一】的回调
    			submitForm('','');
    			 	 
    		  }
    		  ,btn2: function(index, layero){
    		    //按钮【按钮二】的回调
    		    
    		    	//$("#useradd").css('display','none'); 
    		    	
    		  }
    		  ,cancel: function(){ 
    			    //右上角关闭回调
    			    //$("#useradd").css('display','none'); 
    			    
    		 }
    	});
    }
    
    function dialog_edit(data){
    	//debugger;
    	
    	var win = layer.open({
    		  type: 1 //0（信息框，默认）1（页面层）2（iframe层）3（加载层）4（tips层） 
    		  ,title: "编辑机构" //标题
    		  ,skin:""   //layui-layer-lan:蓝色，layui-layer-molv：墨绿色，默认灰色
    		  ,area: ['400px', '620px'] //宽度、高度
    		  ,shade: 0.3
    		  ,offset: 'auto'
    		  ,anim:5 //弹出动画
    		  ,shadeClose: false //弹框出现后，允许点击其它地方关闭
    		  ,content: $("#orgadd").html()     //内容
    		  ,btn: ['确定', '取消'] //只是为了演示
    		  ,success:function(layero){
    			     var mask = $(".layui-layer-shade");
    			     mask.appendTo(layero.parent());
    			     //其中：layero是弹层的DOM对象
    			     $("#orgname").val(data.title);
    			 	 $("#orgcode").val(data.orgcode);
    			 	 $("#f_orgname").val(data.parent_name);
    			 	 $("#f_managerorg").val(data.manager_name);
    			 	 $("#leader").val(data.leader);
    			 	 $("#address").val(data.address);
    			 	 $("#f_descriptor").val(data.descriptor);
    			 	 $("#org_id").val(data.pid);
    			 	 $("#morg_id").val(data.manager_id);    			 	
    			     $('#orgcode').attr("disabled","disabled");

    			}
    		,yes: function(index, layero){
    		    //按钮【按钮一】的回调		    	
    		    	if(submitForm('','')){
    		    		//$("#useradd").css('display','none');
    				 	//layer.close(index);
    		    	}
    			 	 
    		  }
    		  ,btn2: function(index, layero){
    		    //按钮【按钮二】的回调
    		    
    		    	//$("#useradd").css('display','none'); 
    		    	
    		  }
    		  ,cancel: function(){ 
    			    //右上角关闭回调
    			    //$("#useradd").css('display','none'); 
    			    
    		 }
    	});
    }
    
    function submitForm(ckname,ckpassword){
    	//校验
    	//debugger;
    	if($("#orgcode").val().replace(/\s+/g,"").length < 1){
    		layer.msg("请填写正确的机构代码!");	
    		return;
    	}
    	if($("#orgname").val().replace(/\s+/g,"").length < 1){
    		layer.msg("请填写正确的机构名称!");	
    		return;
    	}
    	if($("#orgcode").val() != "10001" && $("#org_id").val().replace(/\s+/g,"").length < 1){
    		layer.msg("请选择上级机构!");	
    		return;
    	}
    	var datastr = '{"orgcode":"'+$("#orgcode").val()+'","orgname":"' +  $("#orgname").val()   +'","parent_id":"' +  $("#org_id").val() +'","manager_id":"' + $("#morg_id").val()  
    		+ '","address":"'+ $("#address").val()  + '","leader":"' + $("#leader").val()  + '","descriptor":"' + $("#descriptor").val()  + '","rname":"系统管理/机构管理/修改","ckname":"'+ckname+'","ckpassword":"'+ckpassword+'"}';
    	
    	if(curopt == 'edit'){
    		$.ajax({
    			type:"post",
    			contentType: "application/json;charset=UTF-8",
    			url: "orgedit",
    			async:false,
    			data:datastr,
    	     	dataType:"json",
    	        success: function(msg) {    //数据提交成功时返回数据
    	        	
    				if(msg.status == "1"){
    					getData();
    					clearorgtbl();
    					layer.closeAll();
    				}else if(msg.status == "1211"){
    					$('#ckname').val('');
						$('#ckpassword').val('');
						ckdialgo_auth();
    	        	}else{
    					layer.msg(msg.desc);	
    				}
    	        },
    	        error : function(e){
    	            alert(e.status);
    	            alert(e.responseText);
    	        }

    		});
    	}else if(curopt == 'add'){
    		$.ajax({
    			type:"post",
    			contentType: "application/json;charset=UTF-8",
    			url: "orgadd",
    			async:false,
    			data:datastr,
    	     	dataType:"json",
    	        success: function(msg) {    //数据提交成功时返回数据
    	        	
    				if(msg.status == "1"){
    					getData();
    					clearorgtbl();
    					layer.closeAll();
    				}else if(msg.status == "1211"){
    					$('#ckname').val('');
						$('#ckpassword').val('');
						ckdialgo_auth();
    	        	}else{
    	        		layer.msg(msg.desc);	
    				}
    	        },
    	        error : function(e){
    	            alert(e.status);
    	            alert(e.responseText);
    	        }

    		});
    	}
    	
    }
    
    function u_remove(ckname,ckpassword){	
    	var datas = insTb.checkStatus();
    	var row = datas[0];
    	if (row){
    		//debugger;
    		if(row.isMenu == 0){
    			layer.msg('该机构下还有下属机构,无法删除!');
    			return;
    		}
    		var datastring = '{"orgcode":"'+ row.orgcode + '","rname":"系统管理/机构管理/删除","ckname":"'+ckname+'","ckpassword":"'+ckpassword+'"}';
    		layer.confirm('确定要删除该机构?', {
    			  btn: ['取消', '确定'] //可以无限个按钮				  
    			}, function(index, layero){
    			  //按钮【按钮一】的回调
    				layer.closeAll();
    			}, function(index){
    				$.ajax({
    					type:"post",
    					contentType: "application/json;charset=UTF-8",
    					url: "orgdelete",
    					async:false,
    					data:datastring,
    			     	dataType:"json",
    			        success: function(msg) {    //数据提交成功时返回数据
    						if(msg.status == "1"){
    							layer.closeAll();
    							getData();									
    						}else if(msg.status == "1211"){
    							$('#ckname').val('');
    							$('#ckpassword').val('');							
    							ckdialgo_auth();
    			        		
    						}else{
    							layer.msg(msg.desc);
    						}						
    						
    			        },
    			        error : function(e){
    			            alert(e.status);
    			            alert(e.responseText);
    			        }

    			});	
    		});
    							
    	}else{
    		layer.msg('需选择操作机构!');
    	}							
    }
    
    function clearorgtbl(){
    	$("#orgcode").val('');
    	$("#orgname").val('');
    	$("#f_orgname").val('');	
    	$("#f_managerorg").val('');
    	$("#address").val('');
    	$("#leader").val('');
    	$("#descriptor").val('');
    	$('#manager_id').val("");
    	$('#parent_id').val("");
    }
    
    function ckdialgo_auth(){
    	layer.open({
    		  type: 1 //0（信息框，默认）1（页面层）2（iframe层）3（加载层）4（tips层） 
    		  ,title: "复核" //标题
    		  ,skin:"layui-layer-lan"   //layui-layer-lan:蓝色，layui-layer-molv：墨绿色，默认灰色
    		  ,area: ['350px', '260px'] //宽度、高度
    		  ,shade: 0.3
    		  ,offset: 'auto'
    		  ,anim:5 //弹出动画
    		  ,shadeClose: false //弹框出现后，允许点击其它地方关闭
    		  ,content: $("#dlgck")     //内容
    		  ,btn: ['确定', '取消'] //只是为了演示
    		  ,success:function(layero){
    			     //var mask = $(".layui-layer-shade");
    			     //mask.appendTo(layero.parent());
    			     $('#ckname').focus();
    			     //其中：layero是弹层的DOM对象
    			}
    		 ,yes: function(index, layero){
    		    //按钮【按钮一】的回调
    		    	userckopt();
    	    		$("#dlgck").css('display','none');
    			 	layer.close(index);
    		    	
    			 	 
    		  }
    		  ,btn2: function(index, layero){
    		    	//按钮【按钮二】的回调
    		    
    		    	$("#dlgck").css('display','none'); 
    		    	
    		  }
    		  ,cancel: function(){ 
    			    //右上角关闭回调
    			    $("#dlgck").css('display','none'); 
    			    
    		 }
    	});
    }

});

$('#ckpassword').on('keydown', function (event) {
    if (event.keyCode == 13) {
    	userckopt();
    	$("#dlgck").css('display','none');
		layer.closeAll();
    }
});

function userckopt(){
	//debugger;
	var ckname = $('#ckname').val();
	if(ckname == ''){
		layer.msg('请填写用户账号!');
		return;
	}
	var ckpassword = $('#ckpassword').val();
	if(curopt == "add"){
		submitForm(ckname,$.base64.encode(ckpassword));
	}else if(curopt == "edit"){
		submitForm(ckname,$.base64.encode(ckpassword));
	}else if(curopt == "del"){
		u_remove(ckname,$.base64.encode(ckpassword));
	}
	
}

function userckopt_cancel(){
	$('#ckname').val('');
	$('#ckpassword').val('');	
}

function dialog_orgselect(flag){
	_getorg = flag;
	layer.open({
		  type: 2 //0（信息框，默认）1（页面层）2（iframe层）3（加载层）4（tips层） 
		  ,title: "选择机构" //标题
		  ,skin:"layui-layer-lan"   //layui-layer-lan:蓝色，layui-layer-molv：墨绿色，默认灰色
		  ,area: ['350px', '400px'] //宽度、高度
		  ,shade: 0.3
		  ,offset: 'auto'
		  ,anim:5 //弹出动画
		  ,shadeClose: false //弹框出现后，允许点击其它地方关闭
		  ,content: 'getorgtree'     //内容
		  ,btn: ['取消'] //只是为了演示	
		  ,success:function (layero,index) {
			  debugger;
              var iframe = window['layui-layer-iframe' + index];              
              iframe.child("orgnization_getorg",flag);
      	  }
		  ,yes: function(index, layero){
		    //按钮【按钮一】的回调
			 	 //$("#orgtree").css('display','none'); 
			 	layer.close(index);
		  }
		  ,cancel: function(index,layero){ 
			    //右上角关闭回调
			    //$("#orgtree").css('display','none'); 
		 }
       });
}

</script>
</body>
</html>